import sqlite3
import re
import os

# 数据库连接
DB_PATH = r'd:\manage1\graduation-project\manage1\manage1\manage\db.sqlite3'
HTML_PATH = r'd:\manage1\graduation-project\manage1\manage1\manage\users.html'

# 备份原始文件
def backup_file():
    backup_path = HTML_PATH + '.bak'
    try:
        with open(HTML_PATH, 'r', encoding='utf-8') as f:
            content = f.read()
        with open(backup_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f'备份文件已创建: {backup_path}')
    except Exception as e:
        print(f'备份文件失败: {e}')

# 从数据库读取用户数据
def get_users_from_db():
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute('SELECT user_type, username, password, status FROM property_user')
        users = cursor.fetchall()
        conn.close()
        print(f'成功从数据库读取 {len(users)} 个用户')
        return users
    except Exception as e:
        print(f'读取数据库失败: {e}')
        return []

# 生成用户列表HTML
def generate_users_html(users):
    rows = []
    for user in users:
        user_type, username, password, status = user
        
        # 确定用户类型徽章
        if user_type == 'admin':
            type_badge = '<span class="badge badge-info">管理员</span>'
        else:
            type_badge = '<span class="badge badge-warning">普通用户</span>'
        
        # 确定状态徽章
        if status == 'active':
            status_badge = '<span class="badge badge-success">已激活</span>'
        else:
            status_badge = '<span class="badge badge-danger">已禁用</span>'
        
        # 密码显示为星号
        password_masked = '********'
        
        # 生成表格行
        row = f"""
        <tr class="table-row-hover">
            <td class="px-6 py-4 whitespace-nowrap">
                {type_badge}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">{username}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {password_masked}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                {status_badge}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <a href="#" class="text-blue-600 hover:text-blue-900 mr-3">查看</a>
                <a href="#" class="text-green-600 hover:text-green-900 mr-3">编辑</a>
                <a href="#" class="text-red-600 hover:text-red-900">删除</a>
            </td>
        </tr>"""
        rows.append(row)
    
    return ''.join(rows)

# 更新HTML文件
def update_html_file(users_html):
    try:
        # 读取文件内容
        with open(HTML_PATH, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 使用正则表达式查找并替换用户列表部分
        # 查找<tbody>标签中的内容
        pattern = r'(<tbody class="bg-white divide-y divide-gray-200">)([\s\S]*?)(</tbody>)'
        
        new_content = re.sub(pattern, f'\\1{users_html}\\3', content, flags=re.MULTILINE)
        
        # 写回文件
        with open(HTML_PATH, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print('成功更新用户列表HTML')
    except Exception as e:
        print(f'更新HTML文件失败: {e}')

# 主函数
def main():
    print('开始更新用户管理页面...')
    
    # 备份原始文件
    backup_file()
    
    # 获取用户数据
    users = get_users_from_db()
    
    if users:
        # 生成新的用户列表HTML
        users_html = generate_users_html(users)
        
        # 更新HTML文件
        update_html_file(users_html)
        
        print('用户管理页面更新完成!')
    else:
        print('没有找到用户数据，页面未更新')

if __name__ == '__main__':
    main()